package io.mft.commons.db;


import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.mft.commons.db.mapper.Pager;
import io.mft.commons.function.response.kv.KVMap;


public class DataPagerProcessor {
	private static final Logger log = LoggerFactory.getLogger(DataPagerProcessor.class);

	public interface DataPagerQuery{
		Pager query(Pager pager,Object...args);
	}

	public	interface DataPagerHandler{

		boolean handle(Pager pager,Object...args);
	}
	private DataPagerQuery pagerQuery;
	private DataPagerHandler handler;
	private int numPerPage;
	public DataPagerProcessor(int numPerPage,DataPagerQuery pagerQuery,DataPagerHandler handler){
		this.pagerQuery=pagerQuery;
		this.handler=handler;
		this.numPerPage=numPerPage;
	}
	public boolean process(Object...args){
		int i=0;
		boolean s=true;
		while (true) {
			try {
				i++;
				Pager pager=new Pager(i, numPerPage);
				pager=this.pagerQuery.query(pager,args);
				List<KVMap> dataList=pager.getDataList();
				if (dataList==null||dataList.size()==0) {
					break;
				}
				s=handler.handle(pager,args);
				if (!s) {
					break;
				}
			} catch (Exception e) {
				log.error("", e);
				break;
			}
		}
		return s;
	}
	
}
